/*
 * 
 */
package com.flying.dcss.userpermissions.action;

import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.flying.dcss.app.CommonHelper;
import com.flying.dcss.app.MD5Helper;
import com.flying.dcss.app.SessionName;
import com.flying.dcss.userpermissions.bo.impl.DcssUser;
import com.flying.dcss.userpermissions.service.impl.UserInfoService;
import com.flying.dcss.userpermissions.service.impl.UserService;
import com.opensymphony.xwork2.ActionSupport;

// TODO: Auto-generated Javadoc
/**
 * The Class EmailVerifyAction.
 */
public class EmailVerifyAction extends ActionSupport {
	
	/** The user info service. */
	private UserInfoService userInfoService;

	/** The user service. */
	private UserService userService;

	/**
	 * Sets the user service.
	 *
	 * @param userService the new user service
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * Sets the user info service.
	 *
	 * @param userInfoService the new user info service
	 */
	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub

		String email = ServletActionContext.getRequest().getParameter("email");
		String verifyCode = ServletActionContext.getRequest().getParameter(
				"verifyCode");

		DcssUser user = userService.getUserByEmail(email);

		if (user == null) {
			PrintWriter out = ServletActionContext.getResponse().getWriter();
			out
					.print("<script>alert('User is not exist!');top.location='account/register.jsp'</script>");
			out.flush();
			out.close();
			return this.ERROR;
		}

		// Before encode.
		String codeString = CommonHelper.getShortDate(user.getCreateTime())
				+ CommonHelper.getShortDate(new Date()) + user.getEmail();

		// After encode.
		String code = MD5Helper.MD5Encode(codeString);

		if (code.equals(verifyCode)) {

			userService.verifyEmail(user.getEmail());

			// Get session.
			HttpSession session = ServletActionContext.getRequest()
					.getSession();
			// Write session.
			session.setAttribute(SessionName.UserSession, user);
			// Set max time.
			session.setMaxInactiveInterval(900);

			return this.SUCCESS;
		} else {
			PrintWriter out = ServletActionContext.getResponse().getWriter();
			out
					.print("<script>alert('Verify code invalid!');top.location='account/register.jsp'</script>");
			out.flush();
			out.close();
			return this.ERROR;
		}
	}

}
